<template>
<div>
  <Modal v-model="polygonMapModal" title="网格边界选取" fullscreen  @on-ok="polygonMapModalConfirm">
    <Card class="cardStrleClass">
      <Row>
        <Col span="12">
          <div style="width: 20px;height: 20px;background-color: #E066FF"></div>
        </Col>
        <Col span="12">
          <span style="color:#E066FF">小区</span>
        </Col>
      </Row>
      <Row>
        <Col span="12">
          <div style="width: 20px;height: 20px;background-color: #3CB371"></div>
        </Col>
        <Col span="12">
          <span style="color:#3CB371">网格</span>
        </Col>
      </Row>
      <div style="margin-top: 20px">
        <Button type="primary"  @click="clearMapPath">重新绘制</Button>
      </div>
    </Card>
    <div id="mapPolygonForGarden" v-if="mapType === 'GD'"></div>
    <HtMap v-if="mapType === 'HT' && cscMapjsonHt"
           ref="HTMAP"
           :center="cscMapjsonHt"
           :updatePolygins_ht="updatePolygins_ht"
           :communityList="communityList"
           :communityListNew="communityListNew"
           @setHtMapJson="setHtMapJson"
    ></HtMap>
  </Modal>
</div>
</template>

<script>
import {
  findGardenForCommunityList,
  findResidentialForCommunityList,
  newGetCompanyInfo
} from '../../../../api/z-new-grid'
import HtMap from '../../../../components/htMap/htMap.vue'
import { autoCenter, autoCenterHT, autoPolygon, getCenter } from '../../../../libs/util'
import { mapTypeChange } from '../../../../libs/mapTypeUtil'

export default {
  name: 'mapPolygonForGrarden',
  components: { HtMap },
  data () {
    return {
      mapType: '',
      updatePolygins_ht: [],
      communityList: [],
      communityListNew: [],
      cscMapjsonHt: '',
      map: null,
      polygonMapModal: false,
      choiceInfo: {},
      companyInfo: {},
      polygons: [],
      operationType: '',
      updateGardenInfo: {},
      updatePolygins: [],
      residentialList: [],
      gardenList: [],
      returnObject: {}
    }
  },
  mounted () {
    if (this.$route.query.mapType === 'HT') {
      this.mapType = 'HT'
    } else {
      this.mapType = mapTypeChange()
    }
  },
  methods: {
    clearMapPath () {
      let ht = autoCenterHT(this.updatePolygins_ht)
      let arr = [[ht[0], ht[1]], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1])], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1]) + 0.002], [parseFloat(ht[0]), parseFloat(ht[1]) + 0.002]]
      this.updatePolygins_ht = JSON.stringify(arr)
      this.initMapHT()
    },
    setHtMapJson (mspJson) {
      this.updatePolygins_ht = mspJson
    },
    init (e) {
      this.choiceInfo = e
      this.newGetCompanyInfo(e)
    },
    newGetCompanyInfo (e) {
      let data = {
        id: e.community_id
      }
      newGetCompanyInfo(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.companyInfo = ret.data.data
          this.operationType = 'create'
          this.polygonMapModal = true
          if (this.mapType === 'GD') {
            this.dispostData()
          }
          if (this.mapType === 'HT') {
            this.dispostDataHT(ret.data.data)
          }
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg })
        }
      })
    },
    dispostDataHT (e) {
      let ht = e.csc_mapjson_ht.split(',')
      let arr = [[ht[0], ht[1]], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1])], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1]) + 0.002], [parseFloat(ht[0]), parseFloat(ht[1]) + 0.002]]
      this.updatePolygins_ht = JSON.stringify(arr)
      this.cscMapjsonHt = e.csc_mapjson_ht.split(',')
      this.initMapHT()
    },
    dispostData () {
      if (this.companyInfo.csc_mapjson === undefined || this.companyInfo.csc_mapjson === '' || !this.companyInfo.csc_mapjson) {
        this.$Notice.error({ title: '社区中心点异常！', desc: '社区中心点为空，请先选择社区中心点！' })
        return
      }
      let _this = this
      setTimeout(function () {
        _this.initMap(getCenter(_this.companyInfo, _this))
      }, 1000)
    },
    updateInit (e, e1) {
      this.choiceInfo = e1
      this.updateGardenInfo = e
      this.operationType = 'update'
      this.polygonMapModal = true
      if (this.mapType === 'HT') {
        // 宏图部分
        if (e.csc_mapjson_ht === undefined) {
          let ht = autoCenterHT(e1.csc_mapjson_ht)
          let arr = [[ht[0], ht[1]], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1])], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1]) + 0.002], [parseFloat(ht[0]), parseFloat(ht[1]) + 0.002]]
          this.updatePolygins_ht = JSON.stringify(arr)
        } else {
          this.updatePolygins_ht = e.csc_mapjson_ht
        }
        this.cscMapjsonHt = autoCenterHT(this.updatePolygins_ht)
        this.initMapHT()
      }
      if (this.mapType === 'GD') {
        this.updatePolygins = e.csc_mapjson
        let x = autoCenter(this.updatePolygins)
        let _this = this
        setTimeout(function () {
          _this.initMap(x)
        }, 1000)
      }
    },
    async initMapHT () {
      if (this.operationType === 'create') {
        await this.findGridResidentialList('')
        await this.findGardenForCommunityList('')
        setTimeout(() => {
          this.$refs.HTMAP.initMap()
        }, 1000)
      }
      if (this.operationType === 'update') {
        await this.findGridResidentialList('')
        await this.findGardenForCommunityList(this.updateGardenInfo.id)
        setTimeout(() => {
          this.$refs.HTMAP.initMap()
        }, 1000)
      }
    },
    initMap (e) {
      this.map = new AMap.Map('mapPolygonForGarden', {
        resizeEnable: true,
        center: new AMap.LngLat(e.lng, e.lat),
        zoom: 15
      })
      this.createMaker(e)
      if (this.operationType === 'create') {
        this.findGridResidentialList('')
        this.findGardenForCommunityList('')
        this.polygons = autoPolygon(e)
        this.createPolygon()
      }
      if (this.operationType === 'update') {
        this.findGridResidentialList('')
        this.findGardenForCommunityList(this.updateGardenInfo.id)
        this.updatePolygon()
      }
    },
    createMaker (e) {
      this.marker = new AMap.Marker({
        position: new AMap.LngLat(e.lng, e.lat)
      })
      this.map.add(this.marker)
    },
    createPolygon () {
      var path = []
      let data = this.polygons
      data.forEach(item => {
        path.push(new AMap.LngLat(item[0], item[1]))
      })
      var Polygon = new AMap.Polygon({
        path: path,
        strokeColor: '#1E9FFF',
        strokeWeight: 2,
        strokeStyle: 'solid',
        strokeOpacity: 1,
        fillOpacity: 0.1,
        fillColor: '#1E9FFF',
        zIndex: 50
      })
      Polygon.on('mouseover', function (e) {
        Polygon.setOptions({
          fillColor: '#FFB800'
        })
      })
      Polygon.on('mouseout', function (e) {
        Polygon.setOptions({
          fillColor: '#1E9FFF'
        })
      })
      this.Polygon = Polygon
      var polyEditor = new AMap.PolyEditor(this.map, this.Polygon)
      polyEditor.open()
      this.map.setFitView([ Polygon ])
      this.map.setZoom(this.map.getZoom() - 2)
      this.map.add(Polygon)
    },
    updatePolygon () {
      var path = []
      let data = JSON.parse(this.updatePolygins)
      data.forEach(item => {
        path.push(new AMap.LngLat(item[0], item[1]))
      })
      var Polygon = new AMap.Polygon({
        path: path,
        strokeColor: '#1E9FFF',
        strokeWeight: 2,
        strokeStyle: 'solid',
        strokeOpacity: 1,
        fillOpacity: 0.1,
        fillColor: '#1E9FFF',
        zIndex: 50
      })
      Polygon.on('mouseover', function (e) {
        Polygon.setOptions({
          fillColor: '#FFB800'
        })
      })
      Polygon.on('mouseout', function (e) {
        Polygon.setOptions({
          fillColor: '#1E9FFF'
        })
      })
      this.Polygon = Polygon
      var polyEditor = new AMap.PolyEditor(this.map, this.Polygon)
      polyEditor.open()
      this.map.setFitView([ Polygon ])
      this.map.setZoom(this.map.getZoom() - 1)
      this.map.add(Polygon)
    },
    findGridResidentialList (e) {
      // console.log(e)
      let data = {
        id: e
      }
      this.communityList = []
      findResidentialForCommunityList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.residentialList = ret.data.data
          this.residentialList.forEach(item => {
            if (this.mapType === 'GD') {
              if (item.csc_mapjson) {
                try {
                  this.findCommunityResidentiallygon(JSON.parse(item.csc_mapjson))
                } catch (e) {
                  console.log(e)
                }
              }
            }
            if (this.mapType === 'HT') {
              if (item.csc_mapjson_ht) {
                try {
                  this.communityList.push(item)
                } catch (e) {
                  // console.log(e)
                }
              }
            }
          })
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg })
        }
      })
    },
    findCommunityResidentiallygon (e) {
      var path = []
      let data = e
      data.forEach(item => {
        path.push(new AMap.LngLat(item[0], item[1]))
      })
      var Polygon = new AMap.Polygon({
        path: path,
        strokeColor: '#E066FF',
        strokeWeight: 2,
        strokeStyle: 'solid',
        strokeOpacity: 1,
        fillOpacity: 0.1,
        fillColor: '#E066FF',
        zIndex: 40
      })
      Polygon.on('mouseover', function (e) {
        Polygon.setOptions({
          fillColor: '#EEDC82'
        })
      })
      Polygon.on('mouseout', function (e) {
        Polygon.setOptions({
          fillColor: '#E066FF'
        })
      })
      this.map.add(Polygon)
    },
    polygonMapModalConfirm () {
      this.returnObject.polygonResult = {}
      if (this.mapType === 'GD') {
        for (var i = 0; i < this.gardenList.length; i++) {
          var path = []
          let data = JSON.parse(this.gardenList[i].csc_mapjson)
          data.forEach(item1 => {
            path.push(new AMap.LngLat(item1[0], item1[1]))
          })
          var Polygon = new AMap.Polygon({
            path: path,
            strokeColor: '#1E9FFF',
            strokeWeight: 2,
            strokeStyle: 'solid',
            strokeOpacity: 1,
            fillOpacity: 0.1,
            fillColor: '#1E9FFF',
            zIndex: 50,
            extData: {
              name: this.gardenList[i].name
            }
          })
          let result = AMap.GeometryUtil.doesRingRingIntersect(this.Polygon.getPath(), Polygon.getPath())
          // console.log('resultresult', result)
          if (result && this.mapTypel === 'GD') {
            // console.log('绘制失败！')
            this.$Notice.error({ title: '绘制失败！', desc: Polygon.getExtData().name + '与当前小区范围重合-1' })
            this.returnObject.polygonResult = {
              name: Polygon.getExtData().name
            }
          }
        }
        this.polygons = this.Polygon.getPath()
        let newpath = []
        this.polygons.forEach(item => {
          let lng = item.lng
          let lat = item.lat
          let point = [lng, lat]
          newpath.push(point)
        })
        var resultPolyons = JSON.stringify(newpath)
        this.returnObject.csc_mapjson = resultPolyons
      }
      if (this.mapType === 'HT') {
        this.returnObject.csc_mapjson_ht = this.updatePolygins_ht
      }
      this.returnObject.mapType = this.mapType
      this.returnObject.residential_id = this.choiceInfo.id
      this.$emit('returnMapInfoForGarden', this.returnObject)
    },
    findGardenForCommunityList (e) {
      let data = {
        id: e,
        residential_id: this.choiceInfo.id
      }
      this.communityListNew = []
      findGardenForCommunityList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.gardenList = ret.data.data
          this.gardenList.forEach(item => {
            if (this.mapType === 'GD') {
              if (item.csc_mapjson) {
                try {
                  this.findCommunityGardenlygon(JSON.parse(item.csc_mapjson))
                } catch (e) {
                  // console.log(e)
                }
              }
            }
            if (this.mapType === 'HT') {
              if (item.csc_mapjson_ht) {
                try {
                  this.communityListNew.push(item)
                } catch (e) {
                  // console.log(e)
                }
              }
            }
          })
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg })
        }
      })
    },
    findCommunityGardenlygon (e) {
      var path = []
      let data = e
      data.forEach(item => {
        path.push(new AMap.LngLat(item[0], item[1]))
      })
      var Polygon = new AMap.Polygon({
        path: path,
        strokeColor: '#3CB371',
        strokeWeight: 2,
        strokeStyle: 'solid',
        strokeOpacity: 1,
        fillOpacity: 0.1,
        fillColor: '#3CB371',
        zIndex: 40
      })
      Polygon.on('mouseover', function (e) {
        Polygon.setOptions({
          fillColor: '#EEDC82'
        })
      })
      Polygon.on('mouseout', function (e) {
        Polygon.setOptions({
          fillColor: '#3CB371'
        })
      })
      this.map.add(Polygon)
    }
  },
  beforeDestroy () {
    this.map && this.map.destroy()
  },
  watch: {
    polygonMapModal (val) {
      if (!val) {
        this.map && this.map.destroy()
      }
    }
  }
}
</script>

<style scoped>
#mapPolygonForGarden {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
.cardStrleClass{
  width:140px;
  position: absolute;
  z-index: 2022;
  top: 25px;
  left: 25px
}
</style>
